﻿
using System;
using NAudio.Wave;
using NAudio.Lame;
using NAudio.Dsp;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NAudio.MediaFoundation;
using NAudio.Wave.SampleProviders;

namespace webapp
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Mp3FileReader m3r1 = new Mp3FileReader(Server.MapPath("~/Source/1.mp3"));
            Mp3FileReader m3r2 = new Mp3FileReader(Server.MapPath("~/Source/2.mp3"));

            WaveStream background = WaveFormatConversionStream.CreatePcmStream(m3r1);
            WaveStream message = WaveFormatConversionStream.CreatePcmStream(m3r2);

            var mixer = new WaveMixerStream32();
            mixer.AutoStop = true;

            var messageOffset = background.TotalTime;
            var messageOffsetted = new WaveOffsetStream(message, TimeSpan.FromSeconds(2), TimeSpan.Zero, message.TotalTime.Subtract(TimeSpan.FromSeconds(30)));

            var background32 = new WaveChannel32(background);
            background32.PadWithZeroes = false;
            // set the volume of background file
            background32.Volume = 0.4f;
            //add stream into the mixer
            mixer.AddInputStream(background32);

            var message32 = new WaveChannel32(messageOffsetted);

            message32.PadWithZeroes = false;
            // set the volume of 2nd mp3 song
            message32.Volume = 0.6f;
            //mixer.AddInputStream(message32);
            //var wave32 = new Wave32To16Stream(mixer);
            //encode the wave stream into mp3
            // write mp3 on the disk

            SmbPitchShiftingSampleProvider SMB = new SmbPitchShiftingSampleProvider(message32.ToSampleProvider(), 4096, 8L, 2.0f);

            using (var resampled = new MediaFoundationResampler(new SampleToWaveProvider16(SMB), new WaveFormat(44100, 1)))
            {
                var desiredBitRate = 0; // ask for lowest available bitrate 
                MediaFoundationEncoder.EncodeToMp3(resampled, Server.MapPath("~/Output/" + Guid.NewGuid().ToString() + ".mp3"), desiredBitRate);
            }

        }
    }
}